package com.ken.student.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.ken.common.dto.signInDto;
import com.ken.common.pojo.*;
import com.ken.common.pojo.Class;
import com.ken.common.result.Result;
import com.ken.student.dto.answerDto;
import com.ken.student.dto.submit_homeworkDto;
import com.ken.student.mapper.studentMapper;
import com.ken.student.pojo.knowledge_statistics;
import com.ken.student.pojo.submit_question;
import com.ken.student.pojo.unitStudyTime;
import com.ken.student.service.studentService;
import com.ken.student.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class studentServiceImpl implements studentService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private studentMapper studentMapper;
    @Override
    public Result<String> signIn(signInDto dto) throws IOException {
        //检验
        String key=dto.getClass_id()+"-"+dto.getStudent_id()+"-"+dto.getCode();
        String state = redisTemplate.opsForValue().get(key);
        if (state==null){
            return Result.error("签到已结束");
        }
        //将状态更新
        studentMapper.change_attendance(dto.getCode(),dto.getStudent_id());
        redisTemplate.opsForValue().set(key, "已签到", redisTemplate.getExpire(key), TimeUnit.SECONDS);
        return Result.success("签到成功");
    }

    @Override
    public List<homeworkVo> getHomeworkById(String student_id) {
        //用student_id获取联系信息
        List<homeworkVo> homeworks = studentMapper.getHomeworkById(student_id);
        return homeworks;
    }

    @Override
    public List<examVo> getExamById(String student_id) {
        List<examVo> exams = studentMapper.getExamById(student_id);
        return exams;
    }

    @Override
    public answer post_answer(answer answer) {
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        answer.setAnswer_id(id);
        System.out.println("搜索问题"+answer.getQuestion_id());
        Question question = studentMapper.getQuestionById(answer.getQuestion_id());
        if(question.getType().equals("填空题")||question.getType().equals("多选题")||question.getType().equals("单选题")){
            answer.setIs_corrected("错误");
            if (question.getAnswer().equals(answer.getContent())){
                answer.setIs_corrected("正确");
            }
            if(!question.getAnswer().equals(answer.getContent())){
                wrong_question wrongQuestion = new wrong_question();
                wrongQuestion.setStudent_id(answer.getStudent_id());
                wrongQuestion.setQuestion_id(answer.getQuestion_id());
                wrongQuestion.setStudent_answer(answer.getContent());
                wrongQuestion.setCorrect_answer(question.getAnswer());
                wrongQuestion.setIs_correct("false");
                wrongQuestion.setWrong_questionId(RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6));
                studentMapper.save_wrongQuestion(wrongQuestion);
            }
        }
        studentMapper.post_answer(answer);
        return answer;
    }

    @Override
    public List<messageVo> getStudentMessage(String student_id) {
        List<messageVo> studentMessage = studentMapper.getStudentMessage(student_id);
        for (messageVo message:studentMessage){
            if (message.getEnd_time().isBefore(LocalDateTime.now())){
                message.setIs_end("1");
            }else {
                message.setIs_end("0");
            }
        }
        return studentMessage;
    }

    @Override
    public List<courseVo> getCourseByStudentId(String student_id) {
        ArrayList<courseVo> courseVos = new ArrayList<>();
        //获取学生所在的所有班级
        List<Class> aClass = studentMapper.get_class(student_id);
        //根据班级获取所有的课程
        for(Class Class:aClass){
            courseVo courseVo = new courseVo();
            course course = studentMapper.get_course(Class.getCourse_id());
            courseVo.setCourse(course);
            courseVo.setAClass(Class);
            courseVos.add(courseVo);
        }
        return courseVos;
    }

    @Override
    public void submit_homework(submit_homeworkDto dto) {
        //将学生的回答保存
        List<submit_question> answers = dto.getAnswers();
        for (submit_question question:answers){
            answer answer = new answer();
            String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
            answer.setAnswer_id(id);
            answer.setHomework_id(dto.getHomework_id());
            answer.setStudent_id(dto.getStudent_id());
            answer.setContent(question.getContent());
            answer.setQuestion_id(question.getQuestion_id());
            Question questionById = studentMapper.getQuestionById(question.getQuestion_id());
            if (questionById.getAnswer().equals(question.getContent())){
                answer.setIs_corrected("正确");
            }else {
                wrong_question wrongQuestion = new wrong_question();
                wrongQuestion.setStudent_id(dto.getStudent_id());
                wrongQuestion.setStudent_answer(question.getContent());
                wrongQuestion.setIs_correct("false");
                wrongQuestion.setQuestion_id(question.getQuestion_id());
                wrongQuestion.setWrong_questionId(RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6));
                wrongQuestion.setCorrect_answer(questionById.getAnswer());
                studentMapper.save_wrongQuestion(wrongQuestion);
                answer.setIs_corrected("错误");
            }
            studentMapper.answer_question(answer);
        }
        //更改作业状态
        studentMapper.changeStudentHomework(dto.getStudent_id(),dto.getHomework_id());
    }

    @Override
    public answer getAnswerById(String student_id, String question_id) {
        return studentMapper.getAnswerById(student_id,question_id);
    }

    @Override
    public boolean is_post(answer answer) {
        return studentMapper.getAnswerByQuestion(answer.getQuestion_id()) != null;
    }

    @Override
    public List<answer> is_post2(List<String> questionIds) {
        ArrayList<answer> answers = new ArrayList<>();
        for(String questionId:questionIds){
            answer answer = studentMapper.getAnswerByQuestion(questionId);
            if (answer==null) {
                return null;
            }
            answers.add(answer);
        }
        return answers;
    }

    @Override
    public List<studyRecord> getLessonRecord(String lesson_id, String student_id) {
        return studentMapper.getLessonRecord(lesson_id, student_id);
    }

    @Override
    public List<knowledge_statistics> getLessonQuestions(String student_id, String lesson_id, String knowledgePoint_id) {
        ArrayList<knowledgePoint> knowledgePoints = new ArrayList<>();
        ArrayList<question_answerVo> questionAnswers = new ArrayList<>();
        ArrayList<knowledge_statistics> knowledge_statistics = new ArrayList<>();
        //先获取根节点自己
        knowledgePoint knowledgePoint = studentMapper.select_knowledgePoint(knowledgePoint_id);
        knowledgePoints.add(knowledgePoint);

        //获取根节点的子节点
        select_knowledgePoint(knowledgePoint_id,knowledgePoints);
       for(knowledgePoint knowledgePoint1:knowledgePoints){
           knowledge_statistics knowledgeStatistics = new knowledge_statistics();
           //将知识点详情填入
           knowledgeStatistics.setKnowledgePointId(knowledgePoint1.getId());
           knowledgeStatistics.setKnowledgePoint_name(knowledgePoint1.getName());
           List<Question> questions = studentMapper.select_questionByKnowledge(knowledgePoint1.getId());
           for(Question question:questions){
               question_answerVo questionAnswerVo = new question_answerVo();
               //获取回答
               answer answer = studentMapper.getAnswerById(student_id, question.getId());
               if (answer!=null){
                   if (answer.getIs_corrected().equals("错误")){
                       knowledgeStatistics.setFalse_num(knowledgeStatistics.getFalse_num()+1);
                   }else {
                       knowledgeStatistics.setCorrect_num(knowledgeStatistics.getCorrect_num()+1);
                   }
                   questionAnswerVo.setQuestion(question);
                   questionAnswerVo.setAnswer(answer);
                   questionAnswers.add(questionAnswerVo);
               }
           }
           knowledge_statistics.add(knowledgeStatistics);
       }
        return knowledge_statistics;
    }

    @Override
    public boolean homework_isPost(String student_id, String homework_id) {
        if (studentMapper.homework_isPost(student_id,homework_id)==null){
            return false;
        }else {
            return !studentMapper.homework_isPost(student_id,homework_id).equals("未提交");
        }
    }

    @Override
    public studyTimeVo getCourseStudyTime(String course_id, String student_id) {
        studyTimeVo studyTimeVo = new studyTimeVo();
        ArrayList<unitStudyTime> unitStudyTimes = new ArrayList<>();
        int CourseTotalTime=0;
        //获取课时的所有单元
        List<unit> units = studentMapper.getUnitByCourse(course_id);
        //遍历每个单元获取其学习的总时间
        for(unit unit:units){
            unitStudyTime unitStudyTime = new unitStudyTime();
            unitStudyTime.setUnit_name(unit.getUnit_name());
            unitStudyTime.setUnit_id(unit.getUnit_id());
            //获取单元的所有课时
            List<lessons> lessons = studentMapper.getLessonByUnit(unit.getUnit_id());
            int total_time=0;
            ArrayList<studyRecord> studyRecords = new ArrayList<>();
            for (lessons Lessons:lessons){
               Integer sumTime = studentMapper.getSumTime(Lessons.getLessons_id(), student_id);
               if (sumTime!=null){
                   total_time=total_time+sumTime;
               }
               List<studyRecord> records = studentMapper.getLessonRecord(Lessons.getLessons_id(), student_id);
               for (studyRecord record:records){
                   record.setLesson_name(Lessons.getLesson_name());
               }
               //System.out.println("获取课时"+Lessons.getLessons_id()+"学习记录"+records);
               studyRecords.addAll(records);
           }
           CourseTotalTime=CourseTotalTime+total_time;
            unitStudyTime.setStudyRecords(studyRecords);
           unitStudyTime.setTotal_time(total_time);
           unitStudyTimes.add(unitStudyTime);
        }
        studyTimeVo.setUnitStudyTimes(unitStudyTimes);
        studyTimeVo.setTotal_time(CourseTotalTime);
        return studyTimeVo;
    }

    @Override
    public List<wrong_question> save_wrongQuestion(List<wrong_question> wrongQuestions) {
        ArrayList<wrong_question> wrong_questions = new ArrayList<>();
        for(wrong_question wrongQuestion : wrongQuestions){
            String id =RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
            wrongQuestion.setWrong_questionId(id);
            wrong_questions.add(wrongQuestion);
            studentMapper.save_wrongQuestion(wrongQuestion);
        }
        return wrong_questions;
    }

    @Override
    public List<wrong_questionVo> get_wrongQuestion(String student_id) {
        ArrayList<wrong_questionVo> wrongQuestionVos = new ArrayList<>();
        List<wrong_question> wrongQuestions = studentMapper.get_wrongQuestion(student_id);
        for(wrong_question wrongQuestion:wrongQuestions){
            wrong_questionVo wrongQuestionVo = new wrong_questionVo();
            Question question = studentMapper.getQuestionById(wrongQuestion.getQuestion_id());
            wrongQuestionVo.setQuestion(question);
            wrongQuestionVo.setWrongQuestion(wrongQuestion);
            wrongQuestionVos.add(wrongQuestionVo);
        }
        return wrongQuestionVos;
    }

    @Override
    public void change_wrongQuestion(String wrong_questionId) {
        studentMapper.change_wrongQuestion(wrong_questionId);
    }

    @Override
    public void delete_wrongQuestion(String wrongQuestionId) {
        studentMapper.delete_wrongQuestion(wrongQuestionId);
    }


    private void select_knowledgePoint(String root,ArrayList<knowledgePoint> knowledgePoints){
        List<knowledgePoint> knowledgePoints1 = studentMapper.select_knowledgePoints(root);
        if (knowledgePoints1==null) return;
        for (knowledgePoint knowledgePoint:knowledgePoints1){
            knowledgePoints.add(knowledgePoint);
            select_knowledgePoint(knowledgePoint.getId(),knowledgePoints);
        }
    }
}
